#include "multiepollserver.h"
#include "epollserver.h"
#include "epolldispatcher.h"
#include "threadpool.h"

class EpollRunner: public Runnable
{
public:
    EpollRunner(ThreadPool* ppool, EpollDispatcher* pdispatcher, EpollServer* pserver):
        m_pool(ppool),m_dispatcher(pdispatcher),m_server(pserver)
    {}

    virtual void run()
    {
        m_server->wait();
    }
    
    void stop()
    {
        m_server->stopWait();
    }

    ~EpollRunner()
    {
        // 注意释放顺序
        // 会调用 dispatcher 的 stop
        m_server->stopWait();
        // 虽然stopwait 了，但pool还是可以收发数据的
        m_pool->stopAll();
        
        delete m_dispatcher;
        delete m_server;
        delete m_pool;
    }
private:
    EpollRunner(const EpollRunner& other);
    EpollRunner& operator=(const EpollRunner& other);

private:
    ThreadPool      *m_pool;
    EpollDispatcher *m_dispatcher;
    EpollServer     *m_server;
};

void MultiEpollServer::wait(unsigned int fdTimeoutSeconds)
{
    vector<EpollRunner*>     vRunner;
    ThreadPool pool(1, m_epollnum);
    
    for(unsigned int i = 0; i < m_epollnum; ++i)
    {
        ThreadPool      *ppool     = new ThreadPool(0,m_pooledthreadnum);
        EpollDispatcher *pdispatch = new EpollDispatcher(*ppool,*m_factory,fdTimeoutSeconds);
        EpollServer     *pserver   = new EpollServer(m_serveraddr,*pdispatch);
        pdispatch->setEpollServer(pserver);/// detecting timeout fd needed,not nessary

        EpollRunner* tmprunner = new EpollRunner(ppool,pdispatch,pserver);
        vRunner.push_back(tmprunner);
        pool.start(*tmprunner);
    }

    // wait
    while(!m_exit)
    {
        Thread::sleep(1000);
    }
    
    vector<EpollRunner*>::iterator itR;
    
    pool.stopAll();
    for (itR = vRunner.begin(); itR != vRunner.end(); ++itR)
    {
        delete *itR;
    }
    vRunner.clear();
}




